#!/bin/bash

source ./envsetup

usage() {
        echo "Usage:"
        echo "  ./run.sh -h | [-t <type>] [-d] [-g]"
        echo "  -h: display usage"
        echo "  -t <type>: noinitrd | initrd (default)"
        echo "  -d: load hard disk image, only effective when type is initramfs"
        echo "  -g: launch gdb"
}

A_TYPE=initrd
while getopts ":t:dhg" opt
do
        case $opt in
        h)
                O_HELP=y
                ;;
        t)
                A_TYPE=$OPTARG
                ;;
        d)
                O_DISK=y
                ;;
        g)
                O_GDB=y
                ;;
        ?)
                echo "there is unrecognized parameter."
                usage
                exit 1
                ;;
    esac
done

if [ $O_HELP -a $O_HELP = y ]; then
        usage
        exit 0;
fi

PARAMS_QEMU="-M virt -m 256M -nographic \
             -kernel $PATH_KERNEL_IMAGE"

if [ $A_TYPE = initrd ]; then
        PARAMS_QEMU+=" -initrd $PATH_INITRAMFS_IMAGE \
                      -append \"nokaslr console=ttyS0\""
elif [ $A_TYPE = noinitrd ]; then
        PARAMS_QEMU+=" -drive file=$PATH_ROOTFS_IMAGE,format=raw,id=hd0 \
                      -device virtio-blk-device,drive=hd0 \
                      -append \"nokaslr root=/dev/vda rw console=ttyS0\""
else
        echo "\"-t $A_TYPE\" is not supported"
        usage
        exit 1;
fi

if [ $O_DISK -a $O_DISK = y ]; then
        if [ ! $A_TYPE = initrd ]; then
                echo "-d only valid when type is initramfs"
                usage
                exit 1;
        fi
        PARAMS_QEMU+=" -drive file=$PATH_DISK_IMAGE,format=raw,id=hd0 \
                      -device virtio-blk-device,drive=hd0"
fi

PARAMS_QEMU+=" -netdev user,id=net0 -device virtio-net-device,netdev=net0"

if [ $O_GDB -a $O_GDB = y ]; then
        PARAMS_QEMU+=" -s -S &"
fi

#set -v

COMMAND="${QEMU} ${PARAMS_QEMU}"
eval $COMMAND

if [ $O_GDB -a $O_GDB = y ]; then
        COMMAND="$GDB $PATH_VMLINUX -d $PATH_LINUX -q -x $PATH_GDBINIT"
        eval $COMMAND
fi
